package com.primus.server.web.controller;

import com.primus.server.entity.store.Store;
import com.primus.server.entity.user.User;
import com.primus.server.security.authentication.SelfUserDetails;
import com.primus.server.service.store.StoreService;
import com.primus.server.service.user.UserService;
import com.primus.server.web.ResponseBase;
import com.primus.server.web.vo.StoreVO;
import com.primus.server.web.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.security.Security;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("user")
public class UserController extends BaseController {

    private final UserService userService;
    private final StoreService storeService;

    @Autowired
    public UserController(UserService userService, StoreService storeService) {
        this.userService = userService;
        this.storeService = storeService;
    }

    @GetMapping(path = "/list")
    public ResponseBase<List<UserVO>> queryUserAll() {
        List<User> users = this.userService.findAll();
        List<UserVO> vos = users.stream().map(this::convertToVO).collect(Collectors.toList());
        return this.success(vos);
    }

    @GetMapping(path = "/{id}")
    public ResponseBase<UserVO> getUserById(@PathVariable Long id) {
        User user = this.userService.findById(id);
        return this.success(this.convertToVO(user));
    }

    @GetMapping(path = "/")
    public ResponseBase<UserVO> getUser() {
        UserVO userVO = this.convertToVO(this.getCurrentUser());
        return this.success(userVO);
    }

    @PostMapping(path = "/upsert")
    public ResponseBase<Void> upsert(@RequestBody UserVO vo) {
        this.userService.save(this.convertToEntity(vo));
        return this.success();
    }

    @DeleteMapping(value = "/{id}")
    public ResponseBase<Void> deleteUser(@PathVariable Long id) {
        this.userService.deleteById(id);
        return this.success();
    }

    @GetMapping(path = "/store")
    public ResponseBase<StoreVO> getStoreByUser() {
        Store store = this.storeService.findByUserId(this.getCurrentUser().getId());
        return this.success(this.transfer(store, new StoreVO()));
    }

    private User convertToEntity(UserVO vo) {
        User user = new User();
        BeanUtils.copyProperties(vo, user);
        return user;
    }

    private UserVO convertToVO(User user) {
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(user, vo);
        return vo;
    }
}
